#!/bin/bash
set -e

echo "🎨 开始前端部署..."

# 配置变量
SERVER_USER="root"
SERVER_HOST="47.109.186.175"
SERVER_PORT="22"
FRONTEND_PATH="/var/www/dx-fun-group/frontend"

# 颜色函数
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# 检查配置
if [ "$SERVER_HOST" = "your-server-ip" ]; then
    print_error "请先配置服务器信息！"
    echo "编辑 scripts/deploy-frontend.sh 文件，修改以下变量:"
    echo "  SERVER_USER=\"your-username\""
    echo "  SERVER_HOST=\"your-server-ip\""
    echo "  SERVER_PORT=\"22\""
    exit 1
fi

# 检查前端构建文件是否存在
if [ ! -d "apps/frontend/dist" ]; then
    print_error "前端构建文件不存在！"
    echo "请先运行: pnpm build:frontend"
    exit 1
fi

# 创建临时部署包
print_info "📦 创建前端部署包..."
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
DEPLOY_PACKAGE="frontend-${TIMESTAMP}.tar.gz"

# 打包前端文件
tar -czf "$DEPLOY_PACKAGE" -C apps/frontend/dist .

print_success "前端文件打包完成: $DEPLOY_PACKAGE"

# 上传到服务器
print_info "📤 上传到服务器..."
scp -o StrictHostKeyChecking=no -P "$SERVER_PORT" "$DEPLOY_PACKAGE" "$SERVER_USER@$SERVER_HOST:/tmp/"

if [ $? -eq 0 ]; then
    print_success "文件上传成功！"
else
    print_error "文件上传失败！"
    exit 1
fi

# 在服务器上部署
print_info "🚀 在服务器上部署..."
ssh -o StrictHostKeyChecking=no -p "$SERVER_PORT" "$SERVER_USER@$SERVER_HOST" << EOF
set -e

echo "🎨 开始前端部署..."

# 创建备份
echo "📦 创建备份..."
if [ -d "$FRONTEND_PATH" ]; then
    sudo mkdir -p /var/backups/dx-fun-group
    sudo cp -r $FRONTEND_PATH /var/backups/dx-fun-group/frontend-backup-\$(date +%Y%m%d-%H%M%S) 2>/dev/null || true
fi

# 创建目录
echo "📁 创建目录..."
sudo mkdir -p $FRONTEND_PATH
sudo chown $SERVER_USER:$SERVER_USER $FRONTEND_PATH

# 解压并部署
echo "📦 解压并部署..."
cd /tmp
tar -xzf $DEPLOY_PACKAGE -C $FRONTEND_PATH

# 设置权限
echo "🔐 设置权限..."
# 检查nginx用户是否存在，如果不存在则使用root
if id "nginx" &>/dev/null; then
    sudo chown -R nginx:nginx $FRONTEND_PATH
elif id "www-data" &>/dev/null; then
    sudo chown -R www-data:www-data $FRONTEND_PATH
else
    sudo chown -R root:root $FRONTEND_PATH
fi
sudo chmod -R 755 $FRONTEND_PATH

# 清理临时文件
echo "🧹 清理临时文件..."
rm -f /tmp/$DEPLOY_PACKAGE

# 重载 Nginx
echo "🌐 重载 Nginx..."
if sudo systemctl is-active --quiet nginx; then
    sudo systemctl reload nginx
    echo "✅ Nginx 重载成功"
else
    echo "⚠️  Nginx 未运行，请手动启动"
fi

echo "✅ 前端部署完成！"
echo "🌐 访问地址: http://$SERVER_HOST"
EOF

# 清理本地临时文件
rm -f "$DEPLOY_PACKAGE"

print_success "前端部署完成！"
echo ""
echo "🌐 访问地址: http://$SERVER_HOST"
echo "📁 部署路径: $FRONTEND_PATH"
echo ""
echo "🔍 如果页面无法访问，请检查："
echo "   1. Nginx 配置是否正确"
echo "   2. 防火墙是否开放 80 端口"
echo "   3. 域名解析是否正确"
